<?php

namespace App\Http\Controllers\Api\Mall;

use DB;

use Illuminate\Http\Request;

use App\Models\ConfigureFunction;

use App\Models\Mall\MallMaster;

use App\Models\Deliver\Deliver;

use App\Models\Customer\Customer;

use App\Models\SysConfig;

use Carbon\Carbon;

use Illuminate\Support\Facades\Redis as Redis;

use App\Http\Controllers\Controller;

class MallLbsController extends Controller
{

    /**
     * 选店初始
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init()
    {

        //查询LBS设置
        $configure = ConfigureFunction::getConfigure(6);

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $configure]);

    }

    /**
     * 查询最近一家门店信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function lately(Request $request)
    {

        $longitude = $request->input('longitude');
        $latitude = $request->input('latitude');
        $wx_location = $request->input('wx_location');

        if ( empty($longitude) || empty($latitude) ) {
            return response()->json(['message' => '缺少定位数据', 'code' => 100001]);
        }

        //如果是微信的定位获得坐标需要将坐标进行转换
        if ( !empty($wx_location) && $wx_location == 1 ) {
            list($latitude, $longitude) = convertDCJ02ToBD09($latitude, $longitude);
        }

        //查询门店列表
        $fixed = 'mallID,mallType,mallName,mallCode,provinceName AS province,cityName AS city,countyName AS county,address,mention,is_send,phone,send_distance,';
        $fixed .= 'SQRT(POW(ABS(longitude-?),2) + POW(ABS(latitude-?),2)) AS line';
        $search_sql = 'SELECT ' . $fixed . ' FROM mall_master WHERE is_show_lbs = 1 AND useFlg=1 ORDER BY line ASC LIMIT 1';
        $mall_data = DB::select($search_sql, [$longitude, $latitude]);
        if ( empty($mall_data) ){
            return response()->json(['message' => '门店列表信息没有找到', 'code' => 100003]);
        }

        foreach ( $mall_data as &$mall ) {

            $mall = collect($mall)->toArray();
            //是否支撑配送：0、不支持配送 1、支持配送但超出配送范围 2、支持配送
            if ($mall['is_send'] == 1) {
                if ($mall['send_distance'] > 0 && $mall['send_distance'] < round($mall['line'] * 100, 2)) {
                    $mall['send'] = 1;
                } else {
                    $mall['send'] = 2;
                }
            } else {
                $mall['send'] = 0;
            }

            if ( round( $mall['line'] * 100, 2 ) < 1 ) {
                $mall['line_distance'] = round( $mall['line'] * 100 * 1000, 2).'m';
            } else{
                $mall['line_distance'] = round($mall['line'] * 100, 2).'km';
            }

            if (empty($mall['phone'])) {
                $mall['phone'] = '';
            }

        }

        //返回数据
        return response()->json([
            'message' => 'ok',
            'code' => 200,
            'data' => $mall_data[0]
        ]);

    }

    /**
     * 根据经纬度获取附近门店
     * @param Request $request
     * array  = array (
     *      'longitude' => 117.238480                        必填   地理位置经度
     *      'latitude' => 31.844126                             必填   地理位置纬度
     *      'keyword' => '合肥新华国际广场店'           不必填   关键词
     *      'wx_location' => 1                                     不必填   是否从微信定位
     *      'page' => 2                                                不必填   页数
     *      'rp' => 10                                                   不必填   每页显示条数
     * )
     * @return \Illuminate\Http\JsonResponse
     */
    public function nearby(Request $request)
    {

        $longitude = $request->input('longitude');
        $latitude = $request->input('latitude');
        $page = $request->input('page');
        $rp = $request->input('rp');
        $limit = $request->input('limit');
        $keyword = $request->input('keyword');
        $wx_location = $request->input('wx_location');

        if (empty($page)) {
            $page = 1;
        }
        if (!empty($rp)) {
            $limit = $rp;
        } else if (empty($limit)) {
            $limit = 10;
        }

        if ( empty($longitude) || empty($latitude) ) {
            return response()->json(['message' => '缺少定位数据', 'code' => 100001]);
        }

        //如果是微信的定位获得坐标需要将坐标进行转换
        if ( !empty($wx_location) && $wx_location == 1 ) {
            list($latitude, $longitude) = convertDCJ02ToBD09($latitude, $longitude);
        }

        //关键词
        $sql = '';
        if ( !empty($keyword) ) {
            $sql .= ' AND ( mallName LIKE "%' . trim($keyword) . '%" OR mallCode LIKE "%' . trim($keyword) . '%")';
        }

        //统计门店数量
        $mall_count = DB::select('SELECT COUNT(*) AS mall_count FROM mall_master WHERE is_show_lbs = 1 AND useFlg = 1' . $sql);
        if ( $mall_count[0]['mall_count'] == 0 ) {
            return response()->json(['message' => '没有门店', 'code' => 100002]);
        }

        //查询门店列表
        $fixed = 'mallID,mallType,mallName,mallCode,provinceName AS province,cityName AS city,countyName AS county,address,mention,is_send,phone,send_distance,';
        $fixed .= 'SQRT(POW(ABS(longitude-?),2) + POW(ABS(latitude-?),2)) AS line';

        $search_sql = 'SELECT ' . $fixed . ' FROM mall_master WHERE is_show_lbs = 1 AND useFlg=1' . $sql ;
        $search_sql .= sprintf(' ORDER BY line ASC LIMIT %d, %d', ($page - 1) * $limit, $limit);
        $mall_data = DB::select($search_sql, [$longitude, $latitude]);
        if ( empty($mall_data) ){
            return response()->json(['message' => '门店列表信息没有找到', 'code' => 100003]);
        }

        foreach ( $mall_data as &$mall ) {

            $mall = collect($mall)->toArray();
            //是否支撑配送：0、不支持配送 1、支持配送但超出配送范围 2、支持配送
            if ($mall['is_send'] == 1) {
                if ($mall['send_distance'] > 0 && $mall['send_distance'] < round($mall['line'] * 100, 2)) {
                    $mall['send'] = 1;
                } else {
                    $mall['send'] = 2;
                }
            } else {
                $mall['send'] = 0;
            }

            if ( round( $mall['line'] * 100, 2 ) < 1 ) {
                $mall['line_distance'] = round( $mall['line'] * 100 * 1000, 2).'m';
            } else{
                $mall['line_distance'] = round($mall['line'] * 100, 2).'km';
            }

            if (empty($mall['phone'])) {
                $mall['phone'] = '';
            }

        }

        //返回数据
        return response()->json([
            'message' => 'ok',
            'code' => 200,
            'data' => [
                'page' => $page,
                'limit' => $limit,
                'count' => $mall_count[0]['mall_count'],
                'list' => $mall_data
            ]
        ]);

    }

    /**
     * 自动选定最近一家支持配送的门店
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function autoMatch(Request $request)
    {

        $longitude = $request->input('longitude');
        $latitude = $request->input('latitude');
        $wx_location = $request->input('wx_location');
        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 0);
        $config_id = $request->input('config_id', 1);
        $store_id = $request->input('store_id', 0);
        $cookie_domain = str_replace('www', '', $_SERVER['SERVER_NAME']);
        $mall_data = [];

        $pcustID = get_customer_id($session_id, $platform);

        if ( !empty($longitude) && !empty($latitude) ) {

            //如果是微信的定位获得坐标需要将坐标进行转换
            if ( !empty($wx_location) && $wx_location == 1 ) {
                list($latitude, $longitude) = convertDCJ02ToBD09($latitude, $longitude);
            }

            //查询最近的一家门店
            $search_sql = 'SELECT *,SQRT(POW(ABS(longitude-?),2) + POW(ABS(latitude-?),2)) AS line FROM mall_master WHERE is_show_lbs = 1 AND is_send=1 AND useFlg=1 ORDER BY line ASC LIMIT 1';
            $mall = DB::select($search_sql, [$longitude, $latitude]);
            $mall_data = $mall[0];
            //是否支撑配送：0、不支持配送 1、支持配送但超出配送范围 2、支持配送
            if ($mall_data['is_send'] == 1) {
                if ($mall_data['send_distance'] > 0 && $mall_data['send_distance'] < round($mall_data['line'] * 100, 2)) {
                    $mall_data['send'] = 1;
                } else {
                    $mall_data['send'] = 2;
                }
            } else {
                $mall_data['send'] = 0;
            }
        }

        if ( empty($longitude) || empty($latitude) || empty($mall_data) || $mall_data['send'] != 2 ) {

            $mall = MallMaster::find($store_id);
            if ( $mall ) {
                $mall_data = $mall->toArray();
                $mall_data['send'] = 0;
            }
        }

        if ( empty($mall_data) ){
            return response()->json(['message' => '没有可用的门店', 'code' => 100001]);
        }

        /**
         * 自动选店
         */

        //判断是自提点还是普通门店
        if ( $mall_data['mallType'] == 2) {
            //查询门店信息
            $temp_mall = MallMaster::find($mall_data['parentId']);
            if ( !$temp_mall ) {
                return response()->json(['message' => '门店信息没有找到', 'code' => 100002]);
            }
            $temp_mall = $temp_mall->toArray();

            $mall_data['zt_id'] = $mall_data['mallID'];
            $mall_data['zt_code'] = $mall_data['mallCode'];
            $mall_data['zt_name'] = $mall_data['mallName'];
            $mall_data['mallID'] = $temp_mall['mallID'];
            $mall_data['mallCode'] = $temp_mall['mallCode'];
            $mall_data['mallName'] = $temp_mall['mallName'];

        } else {
            $mall_data['zt_id'] = 0;
            $mall_data['zt_code'] = null;
            $mall_data['zt_name'] = null;
        }


        if ( $pcustID ) {

            $deliver_data = Deliver::where(['pcustID'=>$pcustID,'mallID'=>$mall_data['mallID'],'zt_id'=>$mall_data['zt_id']])->first();
            if ( !$deliver_data ) {

                //查询会员信息
                $customer = Customer::select('pcustID', 'custID', 'custname', 'cardNo')->find($pcustID);
                if (!$customer) {
                    return response()->json(['message' => '会员信息没有找到', 'code' => 100003]);
                }
                $customer = $customer->toArray();

                $deliver_id = generate_seqno('seqno_custdeliver', true);
                $deliver = new Deliver();
                $deliver->uuid = makeUuid();
                $deliver->timeStamp = Carbon::now();
                $deliver->creator = 'system';
                $deliver->createTime = Carbon::now();
                $deliver->deliverID = $deliver_id;
                $deliver->pcustID = $pcustID;
                $deliver->provinceName = $mall_data['provinceName'];
                $deliver->cityName = $mall_data['cityName'];
                $deliver->countyName = $mall_data['countyName'];
                $deliver->provinceid = $mall_data['provinceid'];
                $deliver->cityid = $mall_data['cityid'];
                $deliver->countyid = $mall_data['countyid'];
                $deliver->address = $mall_data['address'];
                $deliver->custname = !empty($customer['custname']) ? $customer['custname'] : $customer['custID'];
                $deliver->postalCode = '';
                $deliver->mobile = $mall_data['mobile'];
                $deliver->phone = $mall_data['phone'];
                $deliver->mallID = $mall_data['mallID'];
                $deliver->mallName = $mall_data['mallName'];
                $deliver->mallCode = $mall_data['mallCode'];
                $deliver->is_default = 0;
                $deliver->zt_id = $mall_data['zt_id'];
                $deliver->zt_name = $mall_data['zt_name'];
                $deliver->zt_code = $mall_data['zt_code'];
                $deliver->save();
            }

        }


        //保存门店全局redis信息
        $mall_redis_data = array(
            'mallID' => $mall_data['mallID'],
            'mallCode' => $mall_data['mallCode'],
            'mallName' => $mall_data['mallName'],
            'zt_id' => $mall_data['zt_id'],
            'zt_code' => $mall_data['zt_code'],
            'zt_name' => $mall_data['zt_name'],
            'mallType' => $mall_data['mallType'],
            'mention' => $mall_data['mention'],
            'is_send' => $mall_data['is_send'],
            'send' => $mall_data['send'],
            'mall_is_send' => $mall_data['is_send'],
            'send_distance' => $mall_data['send_distance'],
            'send_limit_money' => $mall_data['send_limit_money'],
            'send_limit_points' => $mall_data['send_limit_points'],
            'cityName' => $mall_data['cityName'],
            'mallareaID' => $mall_data['mallareaID'],
            'business_start_time' => $mall_data['business_start_time'],
            'business_end_time' => $mall_data['business_end_time']
        );

        //获取系统配置信息
        $cart_timeout = SysConfig::select('config_value')->where('config_key','G_SHOPPINGCART_TIMEOUT')->first();

        //切换门店清空购物车
        $mallID = redisTransformation( Redis::get($session_id . 'G_CHOOSE_MALL_ID'));
        if ( $mall_data['mallID']  != $mallID ) {
            if ( $pcustID ) {
                Redis::del('shop_cart_'.$pcustID);
            } else {
                Redis::del($session_id . 'shop_cart');
            }
            setcookie('cart_amount', 0, time() + $cart_timeout['config_value'] * 1000, '/', $cookie_domain);
        }

        if ( $config_id == 1 || $config_id == 4 ) {

            Redis::setex( $session_id . 'CUST_SELECTMALL' , 604800 , redisTransformation( $mall_redis_data , 'set' , 604800 ));
            Redis::setex( $session_id . 'G_CHOOSE_MALL_ID' , 604800 , redisTransformation( $mall_data['mallID'] , 'set' , 604800 ));

            if ($mall_data['mallType'] == 2) {
                setcookie('EBSIG_MALL_NAME', urlencode($mall_data['zt_name']), time() + 604800, '/', $cookie_domain);
            } else {
                setcookie('EBSIG_MALL_NAME', urlencode($mall_data['mallName']), time() + 604800, '/', $cookie_domain);
            }

        } else {

            Redis::setex( $session_id . 'SELECT_MALL_' . $config_id, 604800 , redisTransformation( $mall_redis_data , 'set' , 604800 ));
            Redis::setex( $session_id . 'G_CHOOSE_MALL_ID' . $config_id, 604800 , redisTransformation( $mall_data['mallID'] , 'set' , 604800 ));

        }

        //返回数据
        return response()->json([
            'message' => 'ok',
            'code' => 200,
            'data' => ['mall_code' => $mall_data['mallCode'], 'mall_name' => $mall_data['mallName']]
        ]);

    }

}